<template>
  <div>
    <el-form
      :model="settlementForm"
      ref="form"
      label-width="144px"
      class="ccui-form"
      :rules="rules"
    >
      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item label="填报单位：" prop="reportInOrgName">
            <el-select
              v-model="settlementForm.reportInOrgName"
              placeholder="请选择填报单位"
              @change="changeReportInOrgId"
            >
              <el-option
                v-for="item in reportOptions"
                :key="item.orgId"
                :label="item.name"
                :value="item.name"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="结算期间：" prop="settlementStart">
            <el-date-picker
              class="dateClass"
              v-model="settlementForm.settlementStart"
              type="date"
              placeholder="开始日期"
              :picker-options="pickerOptions1"
              @change="handleDate"
              value-format="yyyy-MM-dd"
              :clearable="false"
            >
            </el-date-picker>
            &nbsp; 至
            <el-date-picker
              class="dateClass"
              v-model="settlementForm.settlementEnd"
              type="date"
              placeholder="结束日期"
              :picker-options="pickerOptions2"
              @change="handleDate1"
              value-format="yyyy-MM-dd"
              :clearable="false"
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item label="结算单名称：" prop="settlementName">
            <el-input
              v-model="settlementForm.settlementName"
              @blur="handleTrim('settlementName')"
              placeholder="请输入结算单名称"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="结算单编号：" prop="settlementCode">
            <el-input v-model="settlementForm.settlementCode" disabled />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item label="合同编号：" prop="contractCode">
            <el-input v-model="settlementForm.contractCode" disabled />
            <el-button
              plain
              type="single-number"
              style="margin-left: 10px"
              @click="handleContract"
              >选择
            </el-button>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="合同名称：" prop="contractName">
            <el-input v-model="settlementForm.contractName" disabled />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item label="供应商：" prop="supplierName">
            <el-input v-model="settlementForm.supplierName" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="合同金额：" prop="contractMoney">
            <el-input v-model="settlementForm.contractMoney" disabled />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item label="结算数量：" prop="currSetCount">
            <el-input v-model="settlementForm.currSetCount" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="结算金额：" prop="currSetMoney">
            <el-input v-model="settlementForm.currSetMoney" disabled />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item label="编制人：" prop="reportUsername">
            <el-input v-model="settlementForm.reportUsername" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="编制日期：" prop="reportTime">
            <el-date-picker
              v-model="settlementForm.reportTime"
              type="date"
              placeholder="选择日期"
              value-format="yyyy-MM-dd"
              disabled
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="10">
        <el-col :span="18">
          <el-form-item label="备注：" prop="remarks">
            <el-input
              type="textarea"
              :rows="5"
              maxlength="1000"
              show-word-limit
              placeholder="请输入备注"
              v-model="settlementForm.remarks"
            >
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <!-- 填报单位 -->
    <choose-supplier
      ref="reportInOrgVisible"
      :supplierData="reportInOrgObj"
      @selectPartyB="selectReportInOrg"
    />

    <!-- 合同编号 -->
    <contractDialog
      @numrow="numrow"
      :reportInOrgName="settlementForm.reportInOrgName"
      :reportOrgId="reportOrgId ? reportOrgId : settlementForm.reportInOrgId"
      ref="contractDialog"
    />
  </div>
</template>

<script>
// import chooseSettleContract from "@/basa/components/public/chooseSettleContract";
import contractDialog from "./contractDialog";
import jsList from "../js";
import ChooseSupplier from "../../../../basa/components/public/chooseSupplier";
import { addUrlPerFix } from "@/basa/utils";
import { getUserInfo, getReportInOrgData } from "@/basa/api";
import { getSmpPcConcById } from "../api/settlement-approval";
import Bus from "./bus";

export default {
  props: {
    state: {
      type: String
    },
    detail: {
      type: Object,
      default: () => {}
    },
    myId: {
      type: String
    },
    settlementForm: {
      type: Object
    },
    fileList: {
      type: Array
    },
    settlementList: {
      type: Array,
      default: () => []
    }
  },
  computed: {
    pickerOptions1() {
      // let that = this;
      return {
        disabledDate: function (time) {
          return time.getTime() > Date.now();
        }
      };
    },
    pickerOptions2() {
      let that = this;
      return {
        disabledDate: function (time) {
          if (that.settlementForm.settlementStart == "") {
            return time.getTime() > Date.now() < time.getTime();
          } else {
            return (
              time.getTime() > Date.now() ||
              time.getTime() <
                new Date(that.settlementForm.settlementStart).getTime() -
                  24 * 60 * 60 * 1000
            );
          }
        }
      };
    }
  },
  components: { ChooseSupplier, contractDialog },
  watch: {
    "settlementForm.reportInOrgName": {
      handler(n) {
        if (n) {
          const tempObj = this.reportOptions.find(e => e.name === n);
          this.settlementForm.reportInOrgId = tempObj.orgId;
          this.settlementForm.reportInOrgName = tempObj.name;
          this.reportOrgId = tempObj.orgId;
        }
      },
      deep: true
    }
  },
  data() {
    return {
      dateBool1: true,
      dateBool2: true,
      jsList,
      form: {},
      reportInOrgObj: {
        title: "填报单位查询",
        tableHeadOptions: jsList.reportInOrgTableHead,
        tableData: [],
        recordsTotal: 0,
        formDate: {
          mainType: "A",
          orgid: "",
          pageNo: 1,
          pageSize: 20
        }
      },
      reportOptions: [], // 填报单位
      reportInOrgName: "",
      rules: {
        reportInOrgName: [
          { required: true, message: "请输入填报单位", trigger: "change" }
        ],
        settlementStart: [
          { required: true, message: "请输入结算期间", trigger: "change" }
        ],
        settlementName: [
          { required: true, message: "请输入结算单名称", trigger: "blur" }
        ],
        contractCode: [
          { required: true, message: "请选择合同", trigger: "change" }
        ],
        // supplierName: [
        //     {required: true, message: "请输入供应商", trigger: "change"}
        // ],
        // currSetCount: [
        //   { required: true, message: "请输入结算数量", trigger: "blur" }
        // ],
        // currSetMoney: [
        //   { required: true, message: "请输入结算金额", trigger: "blur" }
        // ],
        currentSettlePayAmtIncludeTax: [
          { required: true, message: "请输入本期支付金额", trigger: "blur" },
          {
            pattern: /(^(\d{0,12})\.(\d{0,8})$)|(^\d{0,12}$)/,
            message: "请输入正确的本期支付金额"
          }
        ],
        paymentNum: [
          { required: true, message: "请输入支付单编号", trigger: "change" }
        ]
      },
      reportOrgId: null
    };
  },
  created() {
    this.addDate();
    this.getUserInfo();
  },
  mounted() {},
  activated() {},
  methods: {
    handleTrim(key) {
      if (!this.settlementForm[key] || this.settlementForm[key] == "") return;
      this.$set(
        this.settlementForm,
        key,
        this.settlementForm[key].replace(/(^\s*)|(\s*)$/g, "")
      );
    },
    handleDate(time) {
      this.settlementForm.settlementEnd = "";
    },
    handleDate1(time) {
      this.dateBool2 = false;
    },
    // 获取当前日期
    addDate() {
      let nowDate = new Date();
      let date = {
        year: nowDate.getFullYear(),
        month: nowDate.getMonth() + 1,
        date: nowDate.getDate()
      };
      this.settlementForm.reportTime =
        date.year + "-" + date.month + "-" + date.date;
    },
    // 获取详情
    getUserInfo() {
      getUserInfo(
        addUrlPerFix(process.env.VUE_APP_BASEP_URL) + "/apis/basap/getUserInfo",
        {}
      ).then(res => {
        this.form.compileUser = res.data.data.userInfo.name;
        this.userOpenId = res.data.data.userInfo.openId;
        this.settlementForm.reportUsername = res.data.data.userInfo.name;
        this.getReportInOrgData(res.data.data.userInfo.openId);
      });
    },
    // 填报单位
    selectReportInOrg(val) {
      if (val.status === "confirm") {
        this.form.reportInOrgName = val.confirmSelect.name;
        this.form.reportInOrgId = val.confirmSelect.id;
        this.settlementForm.reportInOrgId = val.confirmSelect.orgId;
        this.settlementForm.reportInOrgName = val.confirmSelect.name;
      } else {
        switch (val.status) {
          case "search":
            this.reportInOrgObj.formDate = val.formDate;
            break;
          case "pageSize":
            this.reportInOrgObj.formDate.pageSize = val.pageSize;
            break;
          case "pageNo":
            this.reportInOrgObj.formDate.pageNo = val.pageNo;
            break;
          case "reset":
            this.reportInOrgObj.formDate = {
              mainType: "A",
              orgid: "",
              pageNo: 1,
              pageSize: 20
            };
            break;

          default:
            break;
        }
        this.getReportInOrgData(this.userOpenId);
      }
    },
    // 填报信息
    getReportInOrgData(openId) {
      getReportInOrgData({ openIds: [openId] }).then(res => {
        this.reportInOrgObj.tableData = res.data.data[openId];
        this.reportInOrgObj.recordsTotal = res.data.data[openId].length;
        this.reportOptions = res.data.data[openId];
        this.settlementForm.reportInOrgName =
          this.settlementForm.reportInOrgName || this.reportOptions[0].name;
        this.settlementForm.reportInOrgId =
          this.settlementForm.reportInOrgId || this.reportOptions[0].orgId;
      });
    },
    // 提交表单验证
    handleSubmit() {
      return new Promise(resolve => {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (
              1 == 2 &&
              isNaN(this.settlementForm.currentSettlePayAmtIncludeTax)
            ) {
              this.$message({
                message: "本期支付金额中有非法字符，请编辑后保存",
                type: "error",
                showClose: true,
                ccuiCustom: true
              });
              this.settlementForm.currentSettlePayAmtIncludeTax = "";
            } else {
              let newForm = JSON.parse(JSON.stringify(this.settlementForm));
              newForm.compileDate = null; // 暂时设置为空
              newForm.currentSettlePayAmtIncludeTax = Number(
                newForm.currentSettlePayAmtIncludeTax
              );
              return resolve(newForm);
            }
          }

          this.$nextTick(() => {
            const errorFormEl = document.body.querySelector(".is-error");
            if (errorFormEl) {
              errorFormEl.scrollIntoView({
                behavior: "smooth", // 平滑过渡
                block: "start" // 上边框与视窗顶部平齐。默认值
              });
            }
          });
        });
      });
    },
    // 合同编号返回值
    numrow(row) {
      this.settlementForm.contractId = row.id;
      // let contractCode = "";
      let currentNum = 0;
      // contractCode = this.settlementForm.contractCode; //定义一个值，修改合同后，结算单明细和验收单明细页数据应清空
      this.settlementForm.contractCode = row.contractCode;

      // if (contractCode != this.settlementForm.contractCode && contractCode) {
      Bus.$emit("borthsettlementList");
      // }

      this.settlementForm.contractName = row.contractName;
      this.settlementForm.supplierName = row.partyBName;
      this.settlementForm.contractMoney = (+row.initTotalContractPriceIncludeTax).toFixed(2);
      this.settlementForm.supplierId = row.partyBId;
      this.settlementForm.supplierCode = row.partyBExtOid;
      this.settlementForm.partyAName = row.partyAName;
      this.settlementForm.partyBName = row.partyBName;
      getSmpPcConcById({
        concId: row.id,
        flag: 1
      }).then(res => {
        this.settlementForm.smpConcMatLessList =
          res.data.data.smpConcMatLessList;
        this.settlementForm.smpConcMatLessList.forEach(_item => {
          // 运输类 暂时注释
          if (
            _item.thirdCategoriesOfCode &&
            (_item.thirdCategoriesOfCode.substr(0, 4) == "1305" ||
              _item.thirdCategoriesOfCode.substr(0, 4) == "1306" ||
              _item.thirdCategoriesOfCode.substr(0, 4) == "1307" ||
              _item.thirdCategoriesOfCode.substr(0, 4) == "1308" ||
              _item.thirdCategoriesOfCode.substr(0, 4) == "1309" ||
              _item.thirdCategoriesOfCode.substr(0, 6) == "990103")
          ) {
            let uuid = this.generateUUID();
            _item.unitPriceWithTax = "";
            _item.materialCode = _item.materialsCode;
            _item.materialName = _item.materialsName;
            _item.materialState = _item.matDescribe;
            _item.measureUnit = _item.currentMeasuringUnit;
            _item.brand = _item.manufacturer;
            _item.categoryCode = _item.thirdCategoriesOfCode;
            _item.categoryName = _item.thirdCategoriesOfName;
            _item.settlementCount = _item.residualSettlementNumber;
            _item.isOtherCost = 0;
            _item.isMainInventory = 0;
            _item.isCategories = 1; // 自己使用， 用于区分运输类数据
            this.$set(_item, "isMerge", 0);
            _item.moneyWithTax = (+null).toFixed(2);
            _item.moneyWithoutTax = null;

            _item.contractId = res.data.data.smpPcConc.id;
            _item.contractCode = res.data.data.smpPcConc.contractCode;

            _item.materialFirstId = _item.firstId;
            _item.materialId = _item.id;

            _item.mergeUuid = uuid;

            this.settlementList.push(_item);
          }
          // this.settlementList.splice();
          // 累加合同总量
          currentNum += Number(_item.currentNum);
          this.settlementForm.currentNum = currentNum;
        });
        this.settlementForm.smpPcConc = res.data.data.smpPcConc;
        this.settlementForm.thirdCategoriesOfName =
          this.settlementForm.smpPcConc.thirdCategoriesOfName;
        this.settlementForm.currencyCode =
          this.settlementForm.smpPcConc.currencyCode;
        this.settlementForm.currencyName =
          this.settlementForm.smpPcConc.currencyName;
        this.settlementForm.supplierCode =
          this.settlementForm.smpPcConc.companyOrgId;
      });
    },
    changeReportInOrgId(row) {
      const tempObj = this.reportOptions.find(e => e.name === row);
      this.settlementForm.reportInOrgId = tempObj.orgId;
      this.settlementForm.reportInOrgName = tempObj.name;
      // 切换时,清空相应字段值
      if (this.settlementForm.contractCode != "") {
        let arr = [
          "contractCode",
          "contractName",
          "supplierName",
          "contractMoney"
        ];
        arr.forEach(e => {
          this.settlementForm[e] = "";
        });
        Bus.$emit("borthsettlementList");
        this.$nextTick(() => {
          this.$refs.form.clearValidate();
        });
      }
    },
    handleContract() {
      this.$refs["contractDialog"].showContractList();
    },
    generateUUID() {
      var d = new Date().getTime();
      var uuid = "xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx".replace(
        /[xy]/g,
        function (c) {
          var r = (d + Math.random() * 16) % 16 | 0;
          d = Math.floor(d / 16);
          return (c == "x" ? r : (r & 0x3) | 0x8).toString(16);
        }
      );
      return uuid;
    }
  }
};
</script>

<style scoped lang="scss">
.afterCurSettlePayAmtIncludeTax {
  position: absolute;
  top: -25px;
  left: 15px;
  color: #d8d8d8;
}

/deep/ .el-input {
  width: 260px;
}

/deep/ .el-button--single-number {
  width: 46px;
  margin-left: 10px;
  padding: 0 9px;
}

/deep/ .ccui-pre-form-item {
  .el-form-item__label {
    line-height: 16px;
  }
}

/deep/ .dateClass {
  width: 119px !important;
}
</style>
